package com.bytecodezz.app.photoshop.loader.core

import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.net.Uri
import android.util.Log
import androidx.fragment.app.Fragment
import com.bytecodezz.app.photoshop.loader.base.IPhotoshopLoaderStrategy
import com.bytecodezz.app.photoshop.loader.base.ModelTypes
import com.bytecodezz.app.photoshop.loader.strategy.Glide
import com.bytecodezz.app.photoshop.loader.util.Preconditions
import java.io.File

/**
 * 核心管理逻辑
 * 管理构建流程
 */
class PhotoshopLoaderManager : ModelTypes<LoaderBuilder> {

    private object Holder {
        val instance = PhotoshopLoaderManager()
    }

    companion object {
        var builder: LoaderBuilder? = null
        private var loader: IPhotoshopLoaderStrategy? = null
            get() {
                if (field == null) {
                    if (Preconditions.DEBUG)
                        Log.e(Preconditions.TAG, "创建默认图片加载器")
                    field = Glide()
                }
                return field
            }

        fun get() = Holder.instance

        fun with(
            activity: Activity? = null,
            fragment: Fragment? = null,
            context: Context? = null
        ): PhotoshopLoaderManager {
            builder = LoaderBuilder.obtain()
            builder?.with(activity, fragment, context)
            return get()
        }
    }

    /**
     * 设置图片加载器
     */
    fun setHandler(loader: IPhotoshopLoaderStrategy): PhotoshopLoaderManager {
        PhotoshopLoaderManager.loader = loader
        return this
    }

    override fun load(bitmap: Bitmap): LoaderBuilder {
        return builder!!.load(bitmap)
    }

    override fun load(drawable: Drawable): LoaderBuilder {
        return builder!!.load(drawable)
    }

    override fun load(url: String): LoaderBuilder {
        return builder!!.load(url)
    }

    override fun load(uri: Uri): LoaderBuilder {
        return builder!!.load(uri)
    }

    override fun load(file: File): LoaderBuilder {
        return builder!!.load(file)
    }

    override fun load(resourceId: Int): LoaderBuilder {
        return builder!!.load(resourceId)
    }

    override fun load(model: ByteArray): LoaderBuilder {
        return builder!!.load(model)
    }

    fun startLoader(builder: LoaderBuilder) {
        checkParams(builder)
        loader?.let {
            if (Preconditions.DEBUG)
                Log.e(Preconditions.TAG, "开始加载")
            it.loader(builder)
        }
        PhotoshopLoaderManager.builder = null
    }

    private fun checkParams(builder: LoaderBuilder) {
        //检查图片加载基本数据是否完整


        if (Preconditions.DEBUG)
            Log.e(Preconditions.TAG, "参数检查完毕")
    }


}